// 排行榜JavaScript

let currentRank = 'score'; // 当前排行榜类型
let leaderboardData = [];

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    console.log('排行榜页面已加载');
    
    // 初始化
    setupTabs();
    setupLogout();
    
    // 加载数据
    loadLeaderboard('score');
});

// 设置标签页
function setupTabs() {
    const tabButtons = document.querySelectorAll('.tab-btn');
    
    tabButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            const rankType = this.getAttribute('data-rank');
            
            // 更新按钮状态
            tabButtons.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            
            // 加载对应排行榜
            currentRank = rankType;
            loadLeaderboard(rankType);
        });
    });
}

// 设置登出
function setupLogout() {
    const logoutBtn = document.getElementById('logoutBtn');
    if (logoutBtn) {
        logoutBtn.addEventListener('click', function() {
            if (confirm('确定要退出登录吗？')) {
                fetch('/api/logout', {
                    method: 'POST'
                })
                .then(response => response.json())
                .then(data => {
                    window.location.href = '/';
                })
                .catch(error => {
                    console.error('登出失败:', error);
                    window.location.href = '/';
                });
            }
        });
    }
}

// 加载排行榜
function loadLeaderboard(rankType) {
    document.getElementById('leaderboardList').innerHTML = '<div class="loading">正在加载排行榜...</div>';
    
    fetch(`/api/leaderboard?type=${rankType}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 更新统计数据
                document.getElementById('totalRankedUsers').textContent = data.total_users || 0;
                document.getElementById('totalQuizzes').textContent = data.total_quizzes || 0;
                document.getElementById('avgScore').textContent = data.avg_score || 0;
                
                // 显示排行榜
                leaderboardData = data.leaderboard || [];
                displayLeaderboard(leaderboardData, rankType);
            } else {
                document.getElementById('leaderboardList').innerHTML = 
                    '<div class="no-data">加载失败，请刷新重试</div>';
            }
        })
        .catch(error => {
            console.error('加载排行榜失败:', error);
            document.getElementById('leaderboardList').innerHTML = 
                '<div class="no-data">网络错误，请检查连接</div>';
        });
}

// 显示排行榜
function displayLeaderboard(leaderboard, type) {
    const container = document.getElementById('leaderboardList');
    
    if (leaderboard.length === 0) {
        container.innerHTML = '<div class="no-data">暂无排行榜数据</div>';
        return;
    }
    
    const label = {
        'score': { main: '总得分', badge: '分' },
        'quiz': { main: '答题次数', badge: '次' },
        'avg': { main: '平均得分', badge: '分' }
    }[type];
    
    container.innerHTML = leaderboard.map((user, index) => {
        const rank = index + 1;
        const rankClass = rank <= 3 ? `top-${rank}` : '';
        const rankText = rank > 3 ? rank : '';
        
        return `
            <div class="rank-item ${rankClass}">
                <div class="rank-number">${rankText}</div>
                <div class="user-info">
                    <div class="user-name">${user.username}</div>
                    <div class="user-email">${user.email}</div>
                </div>
                <div class="rank-stats">
                    <div class="stat-item">
                        <div class="stat-label">${label.main}</div>
                        <div class="stat-value">${user.stat_value}${label.badge}</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-label">答题次数</div>
                        <div class="stat-value">${user.quiz_count || 0}次</div>
                    </div>
                    ${type === 'score' ? `
                    <div class="stat-item">
                        <div class="stat-label">平均得分</div>
                        <div class="stat-value">${user.quiz_count > 0 ? Math.round(user.stat_value / user.quiz_count) : 0}分</div>
                    </div>
                    ` : ''}
                </div>
            </div>
        `;
    }).join('');
}

